package tank.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;


public class GameClient {

    public static String remoteAddress;
    private static Channel channel = null;

    public static void connect(String ip,int port) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new StringEncoder());
                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(new GameClientHandler());
                        }
                    });
            ChannelFuture cf = bootstrap.connect(ip, port).sync();
            channel = cf.channel();
            channel.closeFuture().sync();
        }finally {
            group.shutdownGracefully();
        }
    }

    public static void send(Object msg){
        channel.writeAndFlush(msg);
    }

    public static void main(String[] args) {
        try {
            GameClient.connect("127.0.0.1",9999);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
